import React, { FC, useContext, useEffect, useMemo } from 'react';
import './index.less';
import { Button, Form } from 'antd';
import { history, Link } from 'umi';
import { KfInput, KfSelect, KfTextArea, useBackendEnum } from 'kf-web-library';
import queryString from 'query-string';
import { SearchPageContext } from '@/pages/SearchPage/common/SearchPageContext';
import usePgSearch, { getLastQueryValue } from '@/pages/SearchPage/common/usePgSearch';
import { useLocalStorageState } from 'ahooks';
import { FormattedMessage } from '@@/exports';
import { HxConfigContext } from '@/layouts/HxConfigContext';
import HxCyTabs from '@/components/HxCyTabs';
import BizSearchBar, { searchTypeMap } from '@/pages/HomePage/BizSearchBar';

interface AdvSearchProps {
}

const AdvSearch: FC<AdvSearchProps> = (props) => {
  const { currentSearch } = usePgSearch();
  const [advSearchTextForm] = Form.useForm();
  const { siteInfo, isZhCN } = useContext(HxConfigContext);
  const { enumDict, enumTypeDict, getBackendEnum } = useBackendEnum();

  const keywordTypeOptions = useMemo(() => {
    return (siteInfo?.articleSearchItems || []).map((item) => {
      return {
        label: getBackendEnum('ConditionParaType', item)?.i18EnumDesc,
        value: item,
        key: item,
      };
    });
  }, [siteInfo?.articleSearchItems]);

  //检索历史
  const [historySearchs, setHistorySearchs] = useLocalStorageState<string[]>('_history_searchs_', {
    defaultValue: [],
  });
  const displayHistorySearch = historySearchs || [];

  useEffect(() => {
    advSearchTextForm.setFieldValue('keyword', getLastQueryValue(currentSearch, 'dsl'));
  }, [currentSearch]);

  return (
    <div className={'full-search-container'}>
      <HxCyTabs
        items={[
          {
            label: '简单检索',
            key: 'simple',
            children: (
              <div className={'simple-search-wrap'}>
                <BizSearchBar
                  showArticleAdvSearch={false}
                  showBizSearchBarExtra={false}
                  //activeKey={searchType?.key}
                  onActiveKeyChange={(val) => {
                  }}
                />
              </div>
            ),
          },
          {
            label: '多项/组合检索',
            key: 'adv',
            children: (
              <div className={'adv-search-wrap'}>
                <div className={'adv-search-container'}>
                  <Form
                    className={'search-bar-adv-form'}
                    id={'search-bar-adv-form'}
                    form={advSearchTextForm}
                    size={'large'}
                    initialValues={{
                      termType: 'AND',
                      keywordType: keywordTypeOptions.length > 0 ? keywordTypeOptions[0].value : '',
                    }}
                    onFinish={(values) => {
                      const { keyword } = values;
                      history.push({
                        pathname: '/search-adv/article',
                        search: queryString.stringify({
                          ...currentSearch,
                          dsl: keyword,
                        }),
                      });
                    }}
                  >
                    <div>
                      <div className={'query-preview-container'}>
                        <div className={'qpc-part'}>
                          <h4>
                            <FormattedMessage id="search.adv-search.terms-tip" />
                          </h4>
                          <div className={'query-preview-content'}>
                            <Form.Item name={'keywordType'} className={'query-item-keyword-type'}>
                              <KfSelect options={keywordTypeOptions} />
                            </Form.Item>
                            <Form.Item name={'term'} className={'query-item-term'}>
                              <KfInput />
                            </Form.Item>
                            <Form.Item name={'termType'} className={'query-item-term-type'}>
                              <KfSelect
                                options={[
                                  { value: 'AND', label: 'AND' },
                                  { value: 'OR', label: 'OR' },
                                  { value: 'NOT', label: 'NOT' },
                                ]}
                              />
                            </Form.Item>
                            <Form.Item className={'query-item-term-add'} shouldUpdate>
                              {(form) => (
                                <Button
                                  type="primary"
                                  disabled={false}
                                  onClick={() => {
                                    const term = form.getFieldValue('term');
                                    if (term) {
                                      let keyword = form.getFieldValue('keyword') || '';
                                      const termType = form.getFieldValue('termType') || 'AND';
                                      const keywordType = form.getFieldValue('keywordType') || 'AB';
                                      const appendVal = `${keywordType}=("${term}")`;
                                      form.setFieldsValue({
                                        keyword: keyword ? `(${keyword}) ${termType} ${appendVal}` : appendVal,
                                      });
                                    }
                                  }}
                                >
                                  <FormattedMessage id="search.adv-search.history-action-add" />
                                </Button>
                              )}
                            </Form.Item>
                          </div>
                        </div>

                        <div className={'qpc-part'}>
                          <h4>
                            <FormattedMessage id="search.adv-search.query-box-tip" />（
                            <Link to={'/search-adv/help'} target={'_blank'}>
                              <FormattedMessage id="search.adv-search.query-box-help" />
                            </Link>
                            ）
                          </h4>
                          <div className={'query-preview-content'}>
                            <Form.Item name={'keyword'} className={'query-item-keyword'}>
                              <KfTextArea autoSize={{ minRows: 4, maxRows: 10 }} />
                            </Form.Item>
                            <Form.Item noStyle={true}>
                              <div className={'query-item-keyword-submit'}>
                                <Button block={true} className={'query-item-keyword-submit-btn'} type="primary" htmlType="submit" disabled={false}>
                                  <FormattedMessage id="text.search" />
                                </Button>
                                <Button block={true} className={'query-item-keyword-reset-btn'} color="default" htmlType="reset" disabled={false}>
                                  <FormattedMessage id="text.reset" />
                                </Button>
                              </div>
                            </Form.Item>
                          </div>
                        </div>
                      </div>

                      {displayHistorySearch.length > 0 && (
                        <div className={'query-preview-container'} style={{ marginTop: 40 }}>
                          <div className={'qpc-part'}>
                            <h4>
                              <FormattedMessage id="search.adv-search.history" />（{displayHistorySearch.length}）
                            </h4>
                            <div className={'query-preview-content'}>
                              <table style={{ width: '100%' }} className={'search-history-table'}>
                                <thead>
                                <tr>
                                  <th style={{ width: 80, textAlign: 'center' }}>
                                    <FormattedMessage id="search.adv-search.history-sn" />
                                  </th>
                                  <th
                                    style={{
                                      wordWrap: 'break-word',
                                      wordBreak: 'break-all',
                                    }}
                                  >
                                    <FormattedMessage id="search.adv-search.history-query" />
                                  </th>
                                  <th style={{ width: 132, textAlign: 'center' }}>
                                    <FormattedMessage id="search.adv-search.history-action" />
                                  </th>
                                </tr>
                                </thead>
                                <tbody>
                                {displayHistorySearch.map((query, index) => (
                                  <tr key={index}>
                                    <td style={{ textAlign: 'center' }}>#{index + 1}</td>
                                    <td>{query}</td>
                                    <td style={{ textAlign: 'center' }}>
                                      <a
                                        onClick={() => {
                                          /*let keyword =
                                    advSearchTextForm.getFieldValue('keyword') ||
                                    '';
                                  if ((keyword || '').trim()) {
                                    advSearchTextForm.setFieldsValue({
                                      keyword: `(${keyword}) AND ${query}`,
                                    });
                                  } else {
                                    advSearchTextForm.setFieldsValue({
                                      keyword: `${query}`,
                                    });
                                  }*/
                                          advSearchTextForm.setFieldsValue({
                                            keyword: `${query}`,
                                          });
                                        }}
                                      >
                                        <FormattedMessage id="search.adv-search.history-action-add" />
                                      </a>
                                      <span style={{ margin: '0 7px' }}>|</span>
                                      <a
                                        onClick={() => {
                                          setHistorySearchs(historySearchs?.filter((i, idx) => idx !== index));
                                        }}
                                      >
                                        <FormattedMessage id="search.adv-search.history-action-del" />
                                      </a>
                                    </td>
                                  </tr>
                                ))}
                                </tbody>
                              </table>
                            </div>
                          </div>
                        </div>
                      )}
                    </div>
                  </Form>
                </div>
              </div>
            ),
          },
          {
            label: '精准检索',
            key: 'precise',
            children: (
              <div className={'precise-search-wrap'}>
                <div className={'precise-name'}>- DOI等于</div>
                <Form
                  onFinish={(values) => {
                    const { keyword } = values;
                    history.push({
                      pathname: '/search-adv/article',
                      search: queryString.stringify({
                        ...currentSearch,
                        dsl: `DI=("${keyword}")`,
                      }),
                    });
                  }}
                >
                  <div className={'precise-name-input'}>
                    <Form.Item name={'keyword'} >
                      <KfInput size={'large'} placeholder={'格式样例：10.7507/1001-5515.202410058'} />
                    </Form.Item>
                  </div>
                  <div className={'precise-submit-wrap'}>
                    <Button htmlType={'submit'} className={'precise-submit'} type={'primary'}>检索</Button>
                  </div>
                </Form>
              </div>
            ),
          },
        ]}
      />
    </div>
  );
};

export default AdvSearch;
